import 'package:aichat_flutter_wallet/module/module_trade/pages/trade_receive.dart';
import 'package:aichat_flutter_wallet/module/module_trade/pages/trade_transfer.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/provider/wallet_index_provider.dart';
import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/set_pass_page.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/user_settings_provider.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/kai_bottom_tip_dialog.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_database/objectbox.dart';
import 'package:lib_util/lib_util.dart';
import '../../../module_common/router/app_route_page_utils.dart';
import '../../../module_common/router/routers.dart';
import 'package:decimal/decimal.dart';

import '../../../module_common/utils/util.dart';
import '../provider/wallet_assets_provider.dart';

class AssetsCardComp extends StatefulWidget {
  void Function()? onTap;

  AssetsCardComp({super.key, this.onTap});

  @override
  _AssetsCardCompState createState() => _AssetsCardCompState();
}

class _AssetsCardCompState extends State<AssetsCardComp> with RouteAware {
  bool isShowError = true;

  bool requestStatus = false;

  DialogType? dialogTypeStatus;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      initStatus();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    /// 路由订阅
    AppRouterPageUtils().routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    /// 取消路由订阅
    AppRouterPageUtils().routeObserver.unsubscribe(this);
    super.dispose();
  }

  // 监听路由 当每次返回当前页面刷新 initStatus
  @override
  void didPopNext() {
    super.didPopNext();
    // 在这里处理页面返回事件
    if (ModalRoute.of(context)!.isCurrent) {
      initStatus();
      // 当回到指定的页面（路径为 '/'）时执行相应的操作
      // 在这里添加您的逻辑代码
    }
  }

  @override
  void didPushNext() {
    super.didPushNext();
    //从当前页面跳转到其他页面时调用
    if (ModalRoute.of(context)!.isCurrent) {
      initStatus();
    }
  }

  // 初始化 状态
  void initStatus() async {
    determineStatus().then((value) {
      if (mounted)
        setState(() {
          isShowError = value == null ? false : true;
        });
    });
  }

  // 确定状态
  // 未设置钱包密码>钱包异常未检测分片>未上传云端
  // 只检测密码和备份
  Future<DialogType?> determineStatus() async {
    try {
      if (!requestStatus) {
        requestStatus = true;
        // 1、未设置密码
        bool isSetPass = context.read<UserSettingsProvider>().hasPassword();
        if (!isSetPass) {
          requestStatus = false;
          return DialogType.PASSWORD;
        }
        // 当前情况下是否已经 上传 服务端 ， 以及谷歌云端
        // 2、钱包异常（本地、云端、服务器一块私钥丢失就会提示）
        // 3、未上传云端
        // 4、换设备没检测到分片
        // 直接 查询 本地  三片
        DialogType? dialogTypeStatus = await context.read<WalletIndexProvider>().checkWalletStatusLocal();
        // if (dialogTypeStatus == null) {
        //   dialogTypeStatus = ;
        // }
        // requestStatus = false;
        // WalletCheckStatus? walletStatus = WalletCheck().walletStatus;
        // 检查本地 的状态 真等于 null;
        // bool hasLocal = false;
        // if (walletStatus != null) {
        //   hasLocal = walletStatus.keyMap['localKey']!.isEmpty ||
        //       walletStatus.keyMap['localKey'] == null;
        // }
        // dialogTypeStatus = await context
        //     .read<WalletIndexProvider>()
        //     .checkWalletStatus(
        //         walletCheckStatus: hasLocal ? null : walletStatus);
        // dialogTypeStatus = await context.read<WalletIndexProvider>().checkWalletStatus(walletCheckStatus: walletStatus);
        requestStatus = false;
        return dialogTypeStatus;
      }
    } catch (e) {
      requestStatus = false;
    }
    return null;
  }

  // 点击显示 弹出层
  void showErrorDialog({DialogType? callBackStatus}) async {
    try {
      final callBackStatus = await determineStatus();
      print('showErrorDialog $callBackStatus');
      if (mounted)
        setState(() {
          isShowError = callBackStatus == null ? false : true;
        });
      WalletCheck.showErrorDialog(callBackStatus: callBackStatus);
      //未设置密码>钱包异常>未上传云端>token过期
      // EasyLoading.generateLoadingFuture(determineStatus(), status: 'loading')
      //     .then((callBackStatus) {
      //   print('callBackStatus===${callBackStatus}');
      //   WalletCheck.showErrorDialog(callBackStatus: callBackStatus);
      // });
      // final callBackStatus = await determineStatus();
    } catch (e) {
      print(e);
    }
  }

  void toggleAssetsShow() {
    context.read<WalletAssetsProvider>().toggleAssetsShow();
    // setState(() {
    //   isShowAssets = !isShowAssets;
    // });
  }

  String callBackAssets(List<Token> tokenList) {
    if (tokenList.length <= 0) {
      return '0.00';
    }
    String result = tokenList.fold('0', (previousValue, element) {
      return Utils.formatDecimalBalance(Decimal.parse(previousValue) + Decimal.parse(element.valueusd ?? '0'),
          fractionDigits: Config.marketFixedNum);
    });
    return result;
  }

  @override
  Widget build(BuildContext context) {
    List<Token> _tokenList =
        ObjectBox().tokenModel.getIsAddedTokenListByWalletInfoId(context.read<TokenListNotifier>().walletInfoId);
    // TODO: implement build
    return Container(
      height: 160.w,
      // width: (MediaQuery.of(context).size.width - 40).w,
      margin: EdgeInsets.only(left: 20.w, right: 20.w),
      child: Stack(
        children: [
          Positioned(
              left: 0,
              top: 0,
              right: 0,
              bottom: 0,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(10.w),
                  child: PublicImage(
                    image: 'assets/images/create_wallet/wallet_assets_card.png',
                    width: double.infinity,
                    height: double.infinity,
                  ))),
          Container(
            padding: EdgeInsets.only(top: 22.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 20.w),
                      child: Text(
                        'Total Asset Valuation',
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          height: 17.w / 12.w,
                          color: Color.fromRGBO(255, 255, 255, .7),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: context.watch<WalletAssetsProvider>().isShowAssets ? 0.w : 7.w,
                    ),
                    Visibility(
                        visible: context.watch<WalletAssetsProvider>().isShowAssets,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            SizedBox(width: 20.w,),
                            Flexible(child: RichText(
                              text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: '\u0024\u00A0',
                                      style:
                                      TextStyle(
                                        fontSize: 26.sp,
                                        fontWeight: FontWeight.w500,
                                        height: 37 / 26,
                                        color: Colors.white,
                                      ),
                                      recognizer: TapGestureRecognizer()
                                        ..onTap = () {
                                          toggleAssetsShow();
                                        },
                                    ),
                                    TextSpan(
                                        text: callBackAssets(context.watch<TokenListNotifier>().tokenList ?? []),
                                        style:TextStyle(
                                          fontSize: 30.sp,
                                          fontWeight: FontWeight.bold,
                                          height: 35.w / 30.w,
                                          color: Colors.white,
                                          fontFamily: '_DIN',
                                        ),
                                        recognizer: TapGestureRecognizer()
                                      ..onTap = () {
                                        toggleAssetsShow();
                                      },
                                    )
                                  ]),
                              overflow: TextOverflow.visible,
                              maxLines: null,
                            )),
                            SizedBox(width: 20.w,),
                          ],
                        )
                    ),
                    Visibility(
                        visible: !context.watch<WalletAssetsProvider>().isShowAssets,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: 20.w,
                            ),
                            InkWell(
                              onTap: () {
                                toggleAssetsShow();
                              },
                              child:  Text(
                                '****',
                                style: TextStyle(
                                  fontSize: 34.sp,
                                  fontWeight: FontWeight.bold,
                                  height: 24.w / 27.w,
                                  color: Colors.white,
                                ),
                              ),
                            )
                          ],
                        )
                       )
                  ],
                )),
                ClipRRect(
                    borderRadius:
                        BorderRadius.only(bottomLeft: Radius.circular(10.w), bottomRight: Radius.circular(10.w)),
                    child: Container(
                      // color: Color.fromRGBO(0, 0, 0, .15),
                      child: Row(
                        children: [
                          Expanded(
                              child: GestureDetector(
                            onTap: () {
                              // 转账
                              bool isSetPass = context.read<UserSettingsProvider>().hasPassword();
                              if (!isSetPass) {
                                Utils.showBottomSheetDialog(
                                    context,
                                    KaiBottomTipDialog(
                                      type: DialogType.PASSWORD,
                                      Confirm: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) => SetPassPage(
                                                    type: '4',
                                                  ),
                                              settings: RouteSettings(name: Routes.rootSetPassRoute)
                                          ),
                                        );
                                      },
                                    ));
                                return;
                              }
                              Token token = _tokenList.firstWhere((token) => token.contractType == 'native');
                              Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                                return TradeTransferPage(
                                  contract: token.contract,
                                );
                              },
                                  settings: RouteSettings(name: Routes.transfer)
                              ));
                            },
                            child: Container(
                              height: 46.w,
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  PublicImage(
                                    image: 'assets/images/create_wallet/transfer.png',
                                    width: 20.w,
                                    height: 20.w,
                                  ),
                                  SizedBox(
                                    width: 10.w,
                                  ),
                                  Text(
                                    'Transfer',
                                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14.sp, color: Colors.white),
                                  )
                                ],
                              ),
                            ),
                          )),
                          Container(
                            width: 1.w,
                            height: 24.w,
                            color: Color.fromRGBO(255, 255, 255, .3),
                          ),
                          Expanded(
                              child: GestureDetector(
                            onTap: () {
                              Token token = _tokenList.firstWhere((token) => token.contractType == 'native');
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (_) {
                                    return TradeReceivePage(contract: token.contract, contractType: token.contractType);
                                  },
                                  settings: RouteSettings(name: Routes.receive),
                                  maintainState: false));
                            },
                            child: Container(
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  PublicImage(
                                    image: 'assets/images/create_wallet/receive.png',
                                    width: 20.w,
                                    height: 20.w,
                                  ),
                                  SizedBox(
                                    width: 10.w,
                                  ),
                                  Text(
                                    'Receive',
                                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 14.sp, color: Colors.white),
                                  )
                                ],
                              ),
                            ),
                          )),
                        ],
                      ),
                    ))
              ],
            ),
          ),
          Visibility(
              visible: isShowError,
              child: Positioned(
                  right: 0,
                  top: 0,
                  child: GestureDetector(
                      child: Container(
                        padding: EdgeInsets.only(left: 0, right: 20.w, top: 20.w, bottom: 10.w),
                        child: PublicImage(
                          image: 'assets/images/wallet/warn.png',
                          width: 21.w,
                          height: 21.w,
                        ),
                      ),
                      onTap: widget.onTap ??
                          () {
                            showErrorDialog();
                          })))
        ],
      ),
    );
  }
}
